package com.fuerda.izb.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import com.fuerda.izb.R

class TextListView : View {
    private var textColor: Int = Color.WHITE
    private var textSize: Float = 16f
    private lateinit var texts: MutableList<String>
    private val paint = Paint().apply {
        color = Color.BLUE
        textSize = this@TextListView.textSize
        isAntiAlias = true //抗锯齿
    }

    constructor(context: Context) : super(context) {
        init(null, 0)
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init(attrs, 0)
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        init(attrs, defStyleAttr)
    }

    private fun init(attrs: AttributeSet?, defStyleAttr: Int) {
        val typedArray = context.obtainStyledAttributes(
            attrs,
            R.styleable.TextListView,
            defStyleAttr,
            0
        )

        try {
            textColor = typedArray.getColor(R.styleable.TextListView_textColor, Color.BLACK)
            textSize = typedArray.getDimension(R.styleable.TextListView_textSize, 16f)
        } finally {
            typedArray.recycle()
        }

        paint.color = textColor
        paint.textSize = textSize
    }

    fun setTexts(texts: MutableList<String>) {
        this.texts = texts
        invalidate()
    }

    override  fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

          if (texts.isEmpty()) {
            return
        }

        // 计算每个文字的宽度
        val textWidths = texts.map { paint.measureText(it) }
        val totalWidth = textWidths.sum()

        // 计算文字之间的间距
        val spacing = (width - totalWidth) / (texts.size - 1)

        // 获取文字的度量信息
        val fontMetrics = paint.fontMetrics
        // 计算文字的竖直居中位置
        val textBaseline = (height / 2f) - (fontMetrics.ascent + fontMetrics.descent) / 2f

        // 计算起始位置
        //var startX = (width - totalWidth) / 2f //这个差不多从中间开始绘制，显然不对
        var startX = 0f


        // 遍历文字列表并绘制
        for (text in texts) {
            canvas.drawText(text, startX, textBaseline, paint)
            startX += textWidths[texts.indexOf(text)] + spacing
        }
    }

}

